package com.cloudfunx.common.vo;

import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.ToString;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @author linjiayu
 */
@Getter
@Setter
@ToString
public class GeneralValueVo {

    private Object k;

    private Object v;

    @SneakyThrows
    public static GeneralValueVo convert(Object t, String k, String v) {
        Class<?> clz = t.getClass();
        Field[] declaredFields = clz.getDeclaredFields();
        GeneralValueVo vo = new GeneralValueVo();
        for (Field declaredField : declaredFields) {
            if (declaredField.getName().equals(k)) {
                Field kf = clz.getDeclaredField(k);
                kf.setAccessible(true);
                Object o = kf.get(t);
                vo.setK(o);
            }
            if (declaredField.getName().equals(v)) {
                Field kf = clz.getDeclaredField(v);
                kf.setAccessible(true);
                Object o = kf.get(t);
                vo.setV(o);
            }
        }
        return vo;
    }

    public static <T> List<GeneralValueVo> convertList(List<T> list, String k, String v) {
        List<GeneralValueVo> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (T t : list) {
                result.add(convert(t, k, v));
            }
        }
        return result;
    }
}
